<?php

namespace BlogBundle\Controller;

use Doctrine\Bundle\DoctrineBundle\Registry as Doctrine;
use Knp\Component\Pager\Paginator;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Templating\EngineInterface;
use \Swift_Mailer;
/**
 * @Route(service="blog.index_controller")
 */
class IndexController extends Controller
{
    private $em;
    private $paginator;
    private $repository = array();

    public function __construct(Doctrine $doctrine, Paginator $paginator,EngineInterface $templating,Swift_Mailer $mailer)
    {
        $this->em = $doctrine->getManager();
        $this->templating = $templating;
        $this->mailer = $mailer;
        $this->paginator = $paginator;
        $this->repository = [
            'category' => $this->em->getRepository('BlogBundle:Category'),
            'post' => $this->em->getRepository('BlogBundle:Post'),
        ];
    }

    /**
     * @Route("/{path}",defaults={"path": null},name="blog_home")
     * @Template
     */
    public function indexAction($path, Request $request)
    {
        $query = $this->repository['post']->createQueryBuilder('p')
            ->select('p')->orderBy('p.published', 'desc');
        if ($path) {
            $category = $this->repository['category']->findOneByPath($path);
            $posts = $this->paginator->paginate(
                $query->where('p.category = :category')
                    ->setParameter('category', $category)->getQuery(),
                $request->query->getInt('page', 1),
                8
            );
        } else {
            $posts = $this->paginator->paginate(
                $query->getQuery(),
                $request->query->getInt('page', 1),
                8
            );
        }
        return compact('posts', 'path');
    }

    /**
     * @Route("/{path}/{pid}",name="blog_post",requirements={"pid": "\d+"})
     * @Template
     */
    public function postAction($path, $pid)
    {
        $post = $this->repository['post']->find($pid);
        if (empty($post)) {
            throw $this->createNotFoundException('没有文章');
        }
        return compact('post', 'path');
    }

}
